package com.example.result

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.util.Log

class MessengerServer : Service() {
    private var handler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {

                MSG_COME -> {
                    val replyTo = msg.replyTo
                    val info = msg.obj
                    replyTo.send(Message.obtain(this).apply {
                        what = MSG_TO
                        obj = "I am MessengerServer,had receive:\n" +
                                "\t${info},\n" +
                                "I reply after 3s"
                    })
                    postDelayed({
                        replyTo.send(Message.obtain(this).apply {
                            what = MSG_TO
                            obj = "I am no think."
                        })
                    }, 3000)
                }
            }

        }
    }
    private var messenger = Messenger(handler)
    override fun onBind(intent: Intent): IBinder? {
        Log.e("MessengerServer", "onBind")
        return messenger.binder
    }

    companion object {
        const val MSG_COME = 1
        const val MSG_TO = 2
    }
}